<template>
	<view>
		<view v-if="!format" class="flex-center">
			<view
			v-for="(item, index) in times"
			:key="index"
			class="flex-center">
				<view
				v-if="index"
				:class="[splitBold ? 'font-medio' : '']"
				:style="{
					padding: '0 8rpx',
					color: splitColor
				}"
				>:</view>
				<view 
				:class="['clear-flex font-bold u-f-26 u-lh-30', `x-counttime${ item.active ? '-active' : '' }`]"
				:style="{
					padding: '4rpx 10rpx',
					color: item.active ? '' : color,
					background: item.active ? '' : bgColor
				}"
				>{{ timeObj[item.key] }}</view>
			</view>
		</view>
		<view v-else>{{ formatText || '' }}</view>
	</view>
</template>

<script>
	import dayjs from 'dayjs'
	const p = (n, s = true) => ((s ? (parseInt(n) > 9 ? '' : '0') : '') +  parseInt(n))
	export default {
		props: {
			time: {
				default: '1970-01-01 00:00:00'
			},
			format: {
				default: ''
			},
			color: {
				default: '#333'
			},
			bgColor: {
				default: '#FFF'
			},
			splitBold: {
				default: false
			},
			splitColor: {
				default: '#333'
			}
		},
		data() {
			let times = [
				{ key: 'hour' }, { key: 'min' }, { key: 'sec' }, { key: 'mim', active: true }
			]
			return {
				times,
				timeObj: {},
				timer: null,
				formatText: ''
			}
		},
		watch: {
			time: {
				handler(n, o) {
					if (n !== o) {
						this.init()
					}
				},
				deep: true,
				immediate: true
			}
		},
		destroyed() {
			this.destoryAction()
		},
		methods: {
			init() {
				this.destoryAction()
				this.timer = setInterval(() => {
					let current = (dayjs(this.time || dayjs()).valueOf() - dayjs().valueOf())
					let time = current / 1000
					time = time < 0 ? 0 : time
					// let d = p(time / (24 * 3600))
					let h = p(time / 3600)
					let m = p(time / 60 % 60)
					let s = p(time % 60)
					let S = p(current / 100 % 10, 0)
					let lessZore = n => n < 0 ? 0 : n;
					this.timeObj = {
						hour: lessZore(h),
						min: lessZore(m),
						sec: lessZore(s),
						mim: lessZore(S)
					}
					if (this.format) {
						this.formatText = this.formatTime(current, this.format)
					}
					this.$emit('change', current)
					if (current <= 0) {
						this.destoryAction()
					}
				}, 100)
			},
			// 传入时间戳（毫秒），最大转换限制为天，最小为秒
			formatTime(time, format = 'D+ H+:m+:s+') {
				time = time < 0 ? 0 : parseInt(time/1000)
				let hasDay = format.indexOf('D+') > -1
				let result = hasDay ? format.replace(/D\+/g, parseInt(time/(24 * 3600)) && p(time/(24 * 3600)) || '' ).replace(/H\+/g, p(time / 3600 % 24)) : format.replace(/H\+/g, p(time / 3600))
				return result.replace(/m\+/g, p(time / 60 % 60))
				.replace(/s\+/g, p(time % 60))
			},
			// 销毁倒计时
			destoryAction() {
				clearInterval(this.timer)
			}
		}
	}
</script>

<style scoped lang="scss">
	.x-counttime {
		color: #333333;
		background: #FFFFFF;
		border-radius: 2rpx;
		
		&-active {
			@extend .x-counttime;
			color: #FFFFFF;
			background: linear-gradient(to right, #F94404 0%, #FD164F 100%);
		}
	}
</style>
